package com.slkj.shilixiaoyuanapp.util;

import android.annotation.SuppressLint;
import android.content.Context;
import android.text.TextUtils;

import com.slkj.shilixiaoyuanapp.data.UserRequest;
import com.slkj.shilixiaoyuanapp.entity.FileEntity;
import com.slkj.shilixiaoyuanapp.entity.UpFileEntity;
import com.slkj.shilixiaoyuanapp.net.CommonResult;
import com.slkj.shilixiaoyuanapp.net.HttpConfig;
import com.slkj.shilixiaoyuanapp.net.HttpHeper;
import com.slkj.shilixiaoyuanapp.net.callback.CommonCallBack;
import com.slkj.shilixiaoyuanapp.net.down.DownloadInfo;
import com.slkj.shilixiaoyuanapp.util.picture.compress.PhotoCompressUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Response;

public class UpdataFileUtil {

    public static Observable<DownloadInfo> downFile(String url,String wjj,String fileName){
      return   HttpHeper.get().updateFileService()
                .downloadFile(url)
                //使用flatMap对获取的Response进行转换，转换成带有DownloadInfo的新的Observable也就是ObservableSource<DownloadInfo>
                .flatMap((Function<Response<ResponseBody>, ObservableSource<DownloadInfo>>) response -> {
//                    Flowable.create(ee ->{
//
//                    }, BackpressureStrategy.BUFFER);
                    
                    return Observable.create(ee -> {
                        InputStream is = null;
                        FileOutputStream fos = null;
                        DownloadInfo downloadInfo = new DownloadInfo();
                        try {

                            //这里文件操作记得加权限管理
                            File parenFile = new File(wjj);//下载的文件夹地址
                            if (!parenFile.exists()) {
                                parenFile.mkdirs();
                            }
                            final File file = new File(parenFile, fileName);//下载的文件名称
                            if (file.exists()) {
                                file.delete();
                            }
                            byte[] buf = new byte[2048];
                            int len;
                            long total = response.body().contentLength();
                            downloadInfo.totalSize = total;
                            downloadInfo.file = file;

                            long current = 0;
                            is = response.body().byteStream();
                            fos = new FileOutputStream(file);
                            while ((len = is.read(buf)) != -1) {
                                current += len;
                                fos.write(buf, 0, len);
                                downloadInfo.currentSize = current;
                                ee.onNext(downloadInfo);//进度回调
                            }
                            ee.onComplete();
                            fos.flush();
                        } catch (Exception e) {
                            e.printStackTrace();
                            ee.onError(e);//错误回调
                        } finally {
                            try {
                                if (is != null) {
                                    is.close();
                                }
                                if (fos != null) {
                                    fos.close();
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });//下载的处理
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    /*
     * 上传多图片
     * */
    public static void UpDataImg(Context context, String folder, List<String> paths, onGetListLitener onGetListLitener) {
        int schoolID = UserRequest.getInstance().getUser().getTeacherSchoolId();
        Map<String, RequestBody> map = new HashMap<>();
        map.put("school", getRequestBody(schoolID + ""));
        map.put("folder", getRequestBody(folder));
        //上传返回的图片或文件path集合
        List<String> list = new ArrayList<>();
        //集合转数组
        String[] path = new String[paths.size()];
        if (paths != null) {
            paths.toArray(path);
        }
        if (path != null && path.length > 0) {
            MultipartBody.Part[] parts = filesToMutipartBody("image", path);
            HttpHeper.get().updateFileService()
                    .updateImg(map, parts)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new CommonCallBack<List<String>>(true,context) {
                        @Override
                        public void onCallBackSuccess(List<String> data) {
                            list.clear();
                            list.addAll(data);
                            onGetListLitener.onListener(list);
                        }
                    });
        }
    }


    /**
     * 上传图片并压缩
     *
     * @param folder
     * @param paths
     * @return
     */
    @SuppressLint("CheckResult")
    public static Observable<CommonResult<List<String>>> UpImgObservable(String folder, List<String> paths) {
        if (paths == null || paths.isEmpty()) {
            List<String> backList = new ArrayList<>();
            CommonResult commonResult = new CommonResult<List<String>>(backList);
            commonResult.setStatus(HttpConfig.RESPONSE_OK);
            return Observable.just(commonResult);
        }
        return Observable.just(paths)
                .subscribeOn(Schedulers.io())
                .flatMap(list -> {
                    List<String> compress = new ArrayList<>();
                    PhotoCompressUtils photoCompressUtils = new PhotoCompressUtils();
                    for (String filePath : list) {
                        compress.add(photoCompressUtils.compress(filePath));
                    }
                    int schoolID = UserRequest.getInstance().getUser().getTeacherSchoolId();
                    Map<String, RequestBody> map = new HashMap<>();
                    map.put("school", getRequestBody(schoolID + ""));
                    map.put("folder", getRequestBody(folder));
                    String[] path = compress.toArray(new String[compress.size()]);
                    MultipartBody.Part[] parts = filesToMutipartBody("image", path);
                    return HttpHeper.get().updateFileService().updateImg(map, parts);
                });

    }





    /**
     * 多文件上传
     * @param folder
     * @param files
     * @return
     */
    @SuppressLint("CheckResult")
    public static Observable<CommonResult<List<UpFileEntity>>> UpFileObservable(String folder, List<FileEntity> files) {
        if (files == null || files.isEmpty()) {
            List<String> backList = new ArrayList<>();
            CommonResult commonResult = new CommonResult<List<String>>(backList);
            commonResult.setStatus(HttpConfig.RESPONSE_OK);
            return Observable.just(commonResult);
        }
        return Observable.just(files)
                .subscribeOn(Schedulers.io())
                .flatMap(list -> {
                    int schoolID = UserRequest.getInstance().getUser().getTeacherSchoolId();
                    Map<String, RequestBody> map = new HashMap<>();
                    map.put("school", getRequestBody(schoolID + ""));
                    map.put("folder", getRequestBody(folder));
                    List<String> paths = new ArrayList<>();
                    for (FileEntity fileEntity: list){
                        paths.add(fileEntity.getPath());
                    }
                    String[] path = paths.toArray(new String[paths.size()]);
                    MultipartBody.Part[] parts = filesToMutipartBody("file", path);
                    return HttpHeper.get().updateFileService().updateFile(map, parts);
                });

    }


    private static MultipartBody.Part[] filesToMutipartBody(String file, String[] path) {
        MultipartBody.Part[] parts = new MultipartBody.Part[path.length];
        int i = 0;
        for (String StringPath : path) {
            if (TextUtils.isEmpty(StringPath)) {
                continue;
            }
            MultipartBody.Part part = getFilePart(StringPath, file);
            if (part == null) {
                continue;
            }
            parts[i] = part;
            i++;
        }
        return parts;
    }

    private static MultipartBody.Part getFilePart(String filePathStr, String key) {
        File file = new File(filePathStr);
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part part = MultipartBody.Part.createFormData(key, file.getName(), requestBody);
        return part;
    }

    public static RequestBody getRequestBody(String value) {
        return RequestBody.create(MediaType.parse("multipart/form-data"), value);
    }

    public interface onGetListLitener {
        void onListener(List<String> list);
    }

}
